/** <a href="http://www.cpupk.com/decompiler">Eclipse Class Decompiler</a> plugin, Copyright (c) 2017 Chen Chao. **/
package com.minierp.validator;

import com.minierp.bean.EstablishmentBean;
import com.minierp.bean.EstablishmentContactBean;
import com.minierp.helper.PageHelper;
import com.minierp.model.Establishment;
import com.minierp.model.EstablishmentContact;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

public class ClieValidator implements Validator {
	public boolean supports(Class clazz) {
		return EstablishmentBean.class.isAssignableFrom(clazz);
	}

	public void validate(Object obj, Errors errors) {
		EstablishmentBean bean = (EstablishmentBean) obj;
		Establishment form = bean.getEstablishment();
		boolean hasError = false;
		if (!hasError
				&& (form.getAddress() == null || form.getAddress().trim()
						.equals(""))) {
			hasError = true;
			errors.rejectValue("establishment.address", "", "请输入『地址』");
		}

		boolean hasItem = false;
		if (!hasError) {
			for (int i = 0; i < bean.getContacts().size(); ++i) {
				EstablishmentContactBean cb = (EstablishmentContactBean) bean
						.getContacts().get(i);
				EstablishmentContact c = cb.getEstablishmentContact();
				if (!cb.getStatus().equals("DELETE")) {
					boolean hasInput = false;
					if (c.getContactName() != null
							&& !c.getContactName().equals("")) {
						hasInput = true;
					} else if (c.getEmail() != null && !c.getEmail().equals("")) {
						hasInput = true;
					} else if (c.getIm() != null && !c.getIm().equals("")) {
						hasInput = true;
					} else if (c.getMark() != null && !c.getMark().equals("")) {
						hasInput = true;
					} else if (c.getMobile() != null
							&& !c.getMobile().equals("")) {
						hasInput = true;
					} else if (c.getPhone() != null && !c.getPhone().equals("")) {
						hasInput = true;
					} else if (c.getPossie() != null
							&& !c.getPossie().equals("")) {
						hasInput = true;
					} else if (c.getSex() != null && !c.getSex().equals("")) {
						hasInput = true;
					}

					if (hasInput) {
						hasItem = true;
						if (c.getContactName() == null
								|| c.getContactName().equals("")) {
							hasError = true;
							errors.rejectValue("contacts", "", "请输入『联系人姓名』");
							break;
						}

						if ((c.getMobile() == null || c.getMobile().equals(""))
								&& (c.getPhone() == null || c.getPhone()
										.equals(""))) {
							hasError = true;
							errors.rejectValue("contacts", "",
									"请输入『联系人手机』或『联系人电话』");
							break;
						}

						if (c.getEmail() != null && !c.getEmail().equals("")
								&& !PageHelper.isEmail(c.getEmail())) {
							hasError = true;
							errors.rejectValue("contacts", "",
									"联系人『Email』格式不正确");
							break;
						}
					} else {
						cb.setStatus("DELETE");
					}
				}
			}
		}

		if (!hasError && !hasItem) {
			hasError = true;
			errors.rejectValue("contacts", "", "『联系人』至少要有一行记录");
		}

	}
}